from rest_framework import generics
from .models import Pet
from .serializers import PetSerializer
from rest_framework.permissions import IsAuthenticated

class PetList(generics.ListCreateAPIView):
    """
    列出当前用户的所有宠物或创建新宠物
    """
    serializer_class = PetSerializer
    permission_classes = [IsAuthenticated]  # 需要登录才能访问
    
    def get_queryset(self):
        # 只返回当前登录用户的宠物
        return Pet.objects.filter(owner=self.request.user)
    
    def perform_create(self, serializer):
        # 自动将当前登录用户设为宠物主人
        serializer.save(owner=self.request.user)

class PetDetail(generics.RetrieveUpdateDestroyAPIView):
    """
    检索、更新或删除单个宠物（只能操作自己的宠物）
    """
    serializer_class = PetSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        # 只允许访问当前登录用户的宠物
        return Pet.objects.filter(owner=self.request.user)